const net = require('net')
// const ipc = require('electron').ipcMain
const { BrowserWindow } = require('electron')
const { Uint8ArrayToString } = require('./index')
var express = require('express')
let client = null

// 创建tcp连接
function createListen(port) {
    if (client) client = null
    client = new net.Socket()

    client.connect(port, '127.0.0.1', function() {
        console.log('TCP connecting!')
        BrowserWindow.getAllWindows().forEach((window) => {
            window.webContents.send('socket-receive', '连接成功')
        })
    })
    client.on('data', function(data) {
        BrowserWindow.getAllWindows().forEach((window) => {
            window.webContents.send('socket-receive', Uint8ArrayToString(new Uint8Array(data)))
        })
    })
}
// 关闭链接
function closeListen() {
    if (client) {
        client.end()
        client = null
        BrowserWindow.getAllWindows().forEach((window) => {
            window.webContents.send('socket-receive', '已断开连接')
        })
    }
}
// 创建http服务
function createHttpServer(port) {
    const app = express()
    app.get('/sendMsg', (req, res) => {
        console.log(req.query)
        if (client) {
            client.write(JSON.stringify(req.query), 'utf-8')
            // client.write(new Uint8Array(req.query), 'utf-8')
            res.send({
                code: 200,
                message: '发送成功',
                data: req.query
            })
        } else {
            res.send({
                code: -1,
                message: '发送失败, Socket未连接',
                data: null
            })
        }
    })
    app.listen(port, () => {
        console.log('start server: http://127.0.0.1:3000')
    })
}
module.exports = {
    createListen, closeListen,
    createHttpServer

}
